package com.yanfei.zero.infrastructure.threads;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

public class FolkJoinTask extends RecursiveTask<Integer> {
    private static final int THRESHOLD = 5;
    private int[] array;
    private int start;
    private int end;

    public FolkJoinTask(int[] array, int start, int end) {
        this.array = array;
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        if (end - start <= THRESHOLD) {
            // 直接计算
            int sum = 0;
            for (int i = start; i < end; i++) {
                sum += array[i];
            }
            return sum;
        } else {
            // Split the task into smaller subtasks
            int mid = (start + end) / 2;
            FolkJoinTask leftTask = new FolkJoinTask(array, start, mid);
            FolkJoinTask rightTask = new FolkJoinTask(array, mid, end);

            leftTask.fork();
            rightTask.fork();

            // Join the results of the subtasks
            int leftResult = leftTask.join();
            int rightResult = rightTask.join();

            // Combine the results
            return leftResult + rightResult;
        }
    }

    public static void main(String[] args) {
        ForkJoinPool pool = new ForkJoinPool();
        int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10,11,12,13,14,15};

        FolkJoinTask task = new FolkJoinTask(array, 0, array.length);
        int result = pool.invoke(task);

        System.out.println("Sum: " + result);
        
        
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

        int sum = numbers.stream() // 不占内存，返回一个 Stream 对象
                        .filter(n -> n % 2 == 0) // 不占内存，返回一个新的 Stream 对象
                        .mapToInt(n -> n * 2) // 不占内存，返回一个新的 IntStream 对象
                        .sum(); // 占用内存，计算结果并返回一个 int 值

        System.out.println(sum); // 输出：20
    }
}
